const moment = require('moment')
const fs = require('fs')
module.exports = class AdminMod extends require('./model') {
  // 用户登录
  static loginAdminMod(username, password) {
    return new Promise((resolve, reject) => {
      let sql = `select * from admin where binary username = "${username}" and password = "${password}"`
      this.query(sql)
        .then((res) => {
          console.log('🚀 ~ res:', res)
          resolve(res)
        })
        .catch((err) => {
          reject('登陆失败')
        })
    })
  }

  // 获取标签分类
  static getTagInfoMod() {
    return new Promise((resolve, reject) => {
      let sql = `select * from tag`
      this.query(sql)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject('查询失败')
        })
    })
  }

  // 更新或发布文章
  static updateArticleMod(articleProps) {
    const { selectedType, articleTitle, articleContent, introducehtml, articleStatus, articleId, imageUrl } =
      articleProps
    const showDate = (new Date().getTime() / 1000).toFixed(0)

    let base64 = imageUrl
    const handleDir = (dir) => {
      return new Promise((resovle, reject) => {
        const exists = fs.existsSync(dir)
        if (exists === false) {
          fs.mkdirSync(dir)
        }
      })
    }
    const path = 'public/images/' + Date.now() + '.png'
    const date = moment(new Date()).format('YYYY-MM').replace(/-/gi, '')
    const day = moment(new Date()).format('DD')
    let dir = `public/images/` + date
    // 创建文件
    handleDir(dir)
    dir += '/' + day
    handleDir(dir)
    base64 = base64.replace(/^data:image\/\w+;base64,/, '') //去掉图片base64码前面部分data:image/png;base64
    const dataBuffer = new Buffer.from(base64, 'base64') //把base64码转成buffer对象，
    dir += '/' + Date.now() + '.png'
    fs.writeFile(dir, dataBuffer, () => '')
    const url = dir.replace(/public/gi, '')

    return new Promise(async (resolve, reject) => {
      let sql =
        'INSERT INTO article (title, content, introduce, add_time, view_count, tag_id, status, url) VALUES (?,?,?,?,?,?,?,?)'
      const arr = [
        articleTitle,
        articleContent,
        introducehtml,
        showDate,
        0,
        selectedType,
        articleStatus,
        url,
        articleId,
      ]

      if (articleId != 0) {
        sql = 'SELECT view_count From article where id = ' + articleId
        const count = await this.query(sql)

        sql =
          'UPDATE article set title = ?, content = ?, introduce = ?, add_time = ?, view_count = ?, tag_id = ?, status = ?, url = ? WHERE id = ?'
        arr[4] = count[0].view_count

        this.query(sql, arr)
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      } else {
        this.query(sql, arr)
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            resolve(err)
          })
      }
    })
  }

  // 获取所有文章信息
  static getArticleListMod() {
    let sql =
      'SELECT article.id as id, ' +
      'article.title as title, ' +
      'article.introduce as introduce, ' +
      'article.add_time as addTime, ' +
      'article.view_count as viewCount, ' +
      'article.status as status, ' +
      'article.url as url, ' +
      'tag.tag_name as tagName, ' +
      'tag.icon as tagIcon ' +
      'FROM article LEFT JOIN tag ON article.tag_id = tag.id'
    return new Promise((resolve, reject) => {
      this.query(sql)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
    })
  }

  // 删除文章
  static async delArticleMod(id) {
    return new Promise((resolve, reject) => {
      let sql = `DELETE FROM article WHERE id = ${id}`
      this.query(sql)
        .then((res) => {
          this.deleteCommentByIdMod(id)
          resolve(res)
        })
        .catch((err) => {
          reject('删除失败')
        })
    })
  }

  // 根据文章id查询文章信息
  static getArticleByIdMod(id) {
    let sql =
      'SELECT article.id as id,' +
      'article.title as title,' +
      'article.introduce as introduce,' +
      'article.content as content,' +
      'article.add_time as addTime,' +
      'article.view_count as viewCount ,' +
      'article.tag_id as tagId ,' +
      'article.url as url ,' +
      'tag.tag_name as tagName ,' +
      'tag.icon as tagIcon ' +
      'FROM article LEFT JOIN tag ON article.tag_id = tag.id ' +
      'WHERE article.id=' +
      id
    return new Promise((resolve, reject) => {
      this.query(sql)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
    })
  }

  // 获取每种文章的数量
  static getDiffTypeArticleInfoMod() {
    let sql = `SELECT tag_id, tag_name, count(*) AS amount FROM article LEFT JOIN tag ON article.tag_id = tag.id GROUP BY tag_id ORDER BY tag_id`
    return new Promise((resolve, reject) => {
      this.query(sql)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
    })
  }

  // 获取近七日访客数量
  static async getNearWeekVisitorMod() {
    let sql = `SELECT FROM_UNIXTIME(visit_date,'%Y-%m-%d') as visitTime, amount FROM web_visit where DATE_SUB(CURDATE(), INTERVAL 6 DAY) <= date(from_unixtime(visit_date))`
    return new Promise((resolve, reject) => {
      this.query(sql)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
    })
  }

  // 获取评论列表
  static getCommentListMod(pageNum, pageSize = 10) {
    let sql =
      'SELECT comment.id as id, ' +
      'comment.article_id as articleId, ' +
      'comment.author as author, ' +
      'comment.content as content, ' +
      'comment.liked as liked, ' +
      'comment.disliked as disliked, ' +
      'comment.add_time as addTime, ' +
      'comment.status as status, ' +
      'article.title as title ' +
      'FROM comment LEFT JOIN article ON article.id = comment.article_id ' +
      `order by addTime desc`
    if (pageNum) {
      const start = (pageNum - 1) * pageSize
      sql += ` limit ${start}, ${pageSize}`
    }
    return new Promise((resolve, reject) => {
      this.query(sql)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
    })
  }

  // 修改文章状态
  static changeArticleStatusMod(id, status) {
    let sql = `UPDATE article SET status = ${status} WHERE id = ${id}`
    return new Promise((resolve, reject) => {
      this.query(sql)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
    })
  }

  // 更新评论
  static changeCommentStatusMod(id, status) {
    let sql = `UPDATE comment SET status = ${status} WHERE id = ${id}`
    return new Promise((resolve, reject) => {
      this.query(sql)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
    })
  }

  // 删除评论
  static deleteCommentByIdMod(id) {
    let sql = `DELETE FROM comment WHERE id = ${id}`
    return new Promise((resolve, reject) => {
      this.query(sql)
        .then((res) => resolve(res))
        .catch((err) => reject(err))
    })
  }
}
